#include "AReVi/arSystem.h"
using namespace AReVi;


//-------------------------------------
// Classe serveur ... broadcast en udp
//-------------------------------------

class Server : public ArObject {
public:
	AR_CLASS(Server)
	AR_CONSTRUCTOR(Server)

protected:
	ArRef<Activity> _act;
	bool _broadcast(ArRef<Activity> act, double dt);

	int _sock;
};

AR_CLASS_DEF(Server, ArObject)

Server::Server(ArCW & arCW) : ArObject(arCW) {
	// Ouverture de la connexion UDP
	_sock = ArSystem::openUDP(1024);
	if (_sock < 0) {
		cerr << "unable to open udp connexion on port 1024" << endl;
	}
	
	_act = Activity::NEW(1.0);
	_act->setBehavior(thisRef(), &Server::_broadcast);
}

Server::~Server() {
	if (_sock >= 0) ArSystem::closeFD(_sock);
	
}

bool Server::_broadcast(ArRef<Activity>, double) {
	StlVector<unsigned int> ips = ArSystem::getUDPBroadcastAddresses();
	for (unsigned int i = 0; i < ips.size(); i++) {
		cout << "Sending hello to " << ips[i] << endl;
		if (ArSystem::sendUDP(_sock, (void *)"hello\n", 7, ips[i], 12345) < 0) {
			cerr << "error while broadcasting" << endl;
		}
	}
	return true;
}







ArRef<Server> server;

ArRef<Scheduler> simulationInit(void) {
	ArRef<Scheduler> sched = RealTimeScheduler::NEW(1e-3);
	server = Server::NEW();
	return(sched);
}

int main(int argc, char ** argv) {
	ArSystem arevi(argc,argv);

	Server::REGISTER_CLASS();

	ArSystem::simulationLoop(&simulationInit);

	return(0);
}
